from django.shortcuts import render, get_object_or_404
from tmp_news.models import LinesDetail, VoteGroup, VoteItem
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views import generic
import json
from random import randint
import copy
from django.views.decorators.clickjacking import xframe_options_exempt

from tmp_news.tools import get_t_article, get_category_list, get_article_list, get_p_article
# Create your views here.
from datetime import datetime


CITY_NAME = ["海门","鄂尔多斯","招远","舟山","齐齐哈尔","盐城","赤峰","青岛","乳山","金昌","泉州","莱西","日照","胶南","南通",
             "拉萨","文登","上海","攀枝花","威海","承德","厦门","丹东","太仓","曲靖","烟台","福州","瓦房店",
             "即墨","抚顺","玉溪","张家口","阳泉","莱州","湖州","昆山","宁波","荣成","连云港","葫芦岛","常熟",
             "淮安","泰州","南宁","营口","惠州","江阴","蓬莱","嘉峪关","延安","太原","昆明",
             "寿光","盘锦","长治","宿迁","咸阳","铜川","平度","佛山","海口","章丘","大连","临汾","吴江",
             "石嘴山","沈阳","苏州","嘉兴","长春","胶州","银川","张家港","三门峡","锦州","南昌","柳州","三亚","自贡","吉林",
             "泸州","西宁","宜宾","呼和浩特","成都","大同","镇江","桂林","张家界","宜兴","北海","西安","金坛","东营","牡丹江",
             "遵义","绍兴","扬州","常州","潍坊","重庆","台州","南京","滨州","贵阳","无锡","本溪","克拉玛依","渭南","马鞍山","宝鸡",
             "焦作","句容","北京","徐州","衡水","包头","绵阳","乌鲁木齐","枣庄","杭州","淄博","鞍山","溧阳","库尔勒","安阳","开封",
             "济南","德阳","温州","九江","邯郸","临安","兰州","沧州","临沂","南充","天津","富阳","泰安","诸暨","郑州","哈尔滨","聊城",
             "芜湖","唐山","平顶山","邢台","德州","济宁","荆州","宜昌","义乌","丽水","洛阳","秦皇岛","株洲","石家庄","莱芜","常德","保定",
             "湘潭","金华","岳阳","长沙","衢州","廊坊","菏泽","合肥","武汉","大庆"]

GD_CITY_NAME = ["深圳","珠海","江门","阳江","肇庆","汕头","湛江","揭阳","汕尾","潮州","云浮","广州","清远","中山","茂名","韶关",
                "东莞","河源","梅州"]
NUM_TIME = 3

def allow_all(response):
    """
    解决跨域的问题
    :param response:
    :return:
    """
    response["Access-Control-Allow-Origin"] = "*"
    response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    response["Access-Control-Max-Age"] = "1000"
    response["Access-Control-Allow-Headers"] = "*"
    return response

# 生产随机数据
def pick_city(citys):
    num_city = len(citys)
    return citys[randint(0, num_city-1)]+'市'

def make_gd_info(source, num_city, heat_rate):
    content = {}
    center_citys = [source]
    city_list = [source]

    # 爆发城市数量
    loops_num = int(num_city / 8)
    for i in range(0, loops_num):
        tmp_city = pick_city(GD_CITY_NAME)
        center_citys.append(tmp_city)
        city_list.append(tmp_city)
    # 连接城市数量
    #广东
    center_citys.append("广州市")
    content['center_citys'] = list(set(center_citys))
    loops_num = num_city - len(content['center_citys'])

    for i in range(0, loops_num):
        city_list.append(pick_city(GD_CITY_NAME))

    # #3个外省
    # for i in range(0, 3):
    #     city_list.append(pick_city(CITY_NAME))

    # 去重名字
    city_list = list(set(city_list))

    content['city_list'] = []

    # 构建连线
    series = []
    f_loop = int(num_city / NUM_TIME)

    # 中心
    coords = list()
    city_2r = [] + content['center_citys']
    for j in range(0, f_loop):
        target = city_list[randint(0, len(city_list)-1)]
        content['city_list'].append(target)
        city_2r.append(target)
        coords.append({
            "from": source,
            "to": target,
            "value": randint(0,10)
        })

    series.append(copy.deepcopy(coords))

    # 第二层
    city_2r = list(set(city_2r))
    city_3r = []
    for j in range(0, f_loop):
        source = city_2r[randint(0,len(city_2r)-1)]
        target = city_list[randint(0, len(city_list) - 1)]
        content['city_list'].append(target)
        city_3r.append(target)
        coords.append({
            "from": source,
            "to": target,
            "value": randint(1,10)
        })

    series.append(copy.deepcopy(coords))
    for j in range(0, heat_rate):
        source = city_3r[randint(0, len(city_3r) - 1)]
        target = pick_city(GD_CITY_NAME)
        content['city_list'].append(target)
        coords.append({
            "from": source,
            "to": target,
            "value": randint(1, 10)
        })

    series.append(coords)
    content['city_list'] = list(set(content['city_list']))

    for city in content['center_citys']:
        if city in content['city_list']:
            content['city_list'].remove(city)

    content['series'] = series
    return content

def make_china_info(source, num_city, heat_rate, detail_info):
    center_citys = []
    city_list = []

    loops_num = int(num_city / 10)
    for i in range(0, loops_num):
        tmp_city = pick_city(CITY_NAME)
        center_citys.append(tmp_city)

    center_citys.append("上海市")
    center_citys.append("北京市")

    # 中心城市数量
    # 去重名字
    detail_info['china_data'] = {}
    detail_info['china_data']['center_citys'] = list(set(center_citys))
    loops_num = int(num_city / 4)
    for i in range(0, loops_num):
        city_list.append(pick_city(CITY_NAME))

    #source to outside
    # 中心
    coords = list()
    coords.append({
        "from": source,
        "to": center_citys[randint(0, len(center_citys) - 1)],
        "value": randint(0, 10)
    })

    # 第一层
    gd_city_list = detail_info['city_list']
    city_2r = [] + center_citys + gd_city_list
    for j in range(0, loops_num):
        target = center_citys[randint(0, len(center_citys) - 1)]
        city_2r.append(target)
        source_city = gd_city_list[randint(0, len(gd_city_list) - 1)]
        coords.append({
            "from": source_city,
            "to": target,
            "value": randint(0, 10)
        })

    #gd to outside
    loops_num = int(heat_rate / 4)
    for j in range(0, loops_num):
        source = city_2r[randint(0, len(city_2r) - 1)]
        target = pick_city(CITY_NAME)
        city_list.append(target)
        coords.append({
            "from": source,
            "to": target,
            "value": randint(1, 10)
        })

    # 去重名字
    detail_info['china_data']['citys'] = list(set(city_list))
    detail_info['china_data']['moveline'] = coords
    return detail_info

def has_content(data):
    city_list = None
    try:
        detail = json.loads(data.detail)
        city_list = detail.get('city_list', None)
    except:
        detail = {}


    if not city_list:
        detail = make_gd_info(data.source_city, data.num_places, data.heat_rate)
        data.detail = json.dumps(detail)
        data.save()

    if not data.is_gd:
        detail = make_china_info(data.source_city, data.num_places, data.heat_rate, detail)
        data.detail = json.dumps(detail)
        data.save()
    return data

def home_page(request):
    return render(request, 'index.html')


@csrf_exempt
def news_dashboard(request, p_id):
    data = get_object_or_404(LinesDetail, pk=p_id)
    data = has_content(data)
    
    response = HttpResponse(data.detail, content_type="application/json")
    return allow_all(response)


@csrf_exempt
def get_news_list(request):
    datas = LinesDetail.objects.order_by('-created')[:6]

    content = []

    for data in datas:
        data = has_content(data)
        content.append({
            'id': data.id,
            'tital': data.news_name,
            'source': data.source_city,
            'created': data.created.strftime("%Y-%m-%d %H:%M:%S")
        })

    response = HttpResponse(json.dumps(content), content_type="application/json")
    return allow_all(response)

@xframe_options_exempt
def get_dashboard(request, p_id):
    return render(request, 'news_page.html', {"page":str(p_id)})

@xframe_options_exempt
def get_china_dashboard(request, p_id):
    return render(request, 'news_page_china.html', {"page":str(p_id)})

class NewsIndexView(generic.ListView):
    model = LinesDetail
    template_name = "news_index.html"
    paginate_by = 10   # 一个页面显示的条目
    context_object_name = "news_list"

# 投票页面

class VoteIndexView(generic.ListView):
    model = VoteGroup
    template_name = "vote_index.html"
    paginate_by = 10   # 一个页面显示的条目
    context_object_name = "vote_list"

@csrf_exempt
def vote_detail(request, p_id):
    vote = get_object_or_404(VoteGroup, pk=p_id)
    items = VoteItem.objects.filter(vote=vote)
    content = {"title":vote.title}
    if len(items) > 0:
        content['items'] = [x.to_json() for x in items]
    response = HttpResponse(json.dumps(content), content_type="application/json")
    return allow_all(response)

def vote_page(request, p_id):
    vote = get_object_or_404(VoteGroup, pk=p_id)
    items = VoteItem.objects.filter(vote=vote)
    content = {"vote":vote}
    content['items'] = items
    return render(request, 'vote_page.html', content)


def add_count(request, p_id):
    if request.method == 'POST':
        item = get_object_or_404(VoteItem, pk=p_id)
        item.vote_count += 1
        item.save()
        return HttpResponse(json.dumps({'msg':"Ok", "count":item.vote_count}), content_type="application/json")


@xframe_options_exempt
def get_map(request, p_id):
    return render(request, 'vote_map.html', {"page":str(p_id)})


# 实时获取内网新华网最新的新闻，暂不保存
def get_xinhuanews(request):
    num = request.GET.get('num', 3)
    today = datetime.today().strftime('%Y-%m-%d')
    beginDate = request.GET.get('startDate',today)
    endDate = request.GET.get('endDate', today)

    keyword = request.GET.get('keyword', '')

    title = request.GET.get('title', '')

    category = request.GET.get('category', '')

    res = get_t_article(
        startDate=beginDate,
        endDate=endDate,
        total=num,
        keyword=keyword,
        title=title,
        category=category
    )

    if len(res)>0:
        return allow_all(JsonResponse({'is_error':False, 'data':res}))

    return allow_all(JsonResponse({'is_error': True, 'data': []}))


# 实时获取内网新华网最新的图片新闻，暂不保存
def get_xinhua_picnews(request):
    num = request.GET.get('num', 10)
    today = datetime.today().strftime('%Y-%m-%d')
    beginDate = request.GET.get('startDate',today)

    res = get_p_article(
        startDate=beginDate,
        total=num,
    )

    if len(res)>0:
        return allow_all(JsonResponse({'is_error':False, 'data':res}))

    return allow_all(JsonResponse({'is_error': True, 'data': []}))


# 实时获取内网新华网最新的新闻,不分组
def get_xinhuanews_all(request):
    num = request.GET.get('num', 10)
    res = get_article_list(total=num)

    if len(res)>0:
        return allow_all(JsonResponse({'is_error':False, 'data':res}))

    return allow_all(JsonResponse({'is_error': True, 'data': []}))


def xinhuanews_page(request):
    category_list = get_category_list()
    return render(request, 'xinhuanews.html', {"category_list":category_list})